package com.zhucan.tenant.datasource;


import com.zhucan.tenant.datasource.extension.DatasourceTenantDatabaseNameGenerator;
import com.zhucan.tenant.datasource.extension.DatasourceTenantProperties;
import com.zhucan.tenant.datasource.extension.TenantProvider;
import com.zhucan.tenant.datasource.mybatis.DatasourceDynamicTableNameInnerInterceptor;
import com.zhucan.tenant.datasource.mybatis.MybatisPlusTenantInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author My Lord zhuCan
 * @description 多租户的自动装配
 * @since 2022-12-09 11:46
 **/
@ConditionalOnProperty(prefix = "tenant.datasource", name = "enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnBean(value = {TenantProvider.class})
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({DatasourceTenantProperties.class})
public class DatasourceTenantAutoConfiguration {

    @Bean
    @ConditionalOnBean(TenantProvider.class)
    @ConditionalOnMissingBean(DatasourceContextHolder.class)
    public DatasourceContextHolder mongoContextHolder(DatasourceTenantDatabaseNameGenerator generator,
                                                      TenantProvider provider) {
        return new DatasourceContextHolder.DefaultDatasourceContextHolder(generator, provider);
    }


    @Bean
    @ConditionalOnMissingBean(DatasourceTenantDatabaseNameGenerator.class)
    public DatasourceTenantDatabaseNameGenerator mongoTenantDatabaseNameGenerator(Environment environment,
                                                                                  DatasourceTenantProperties mongoTenantProperties) {
        return new DatasourceTenantDatabaseNameGenerator.DefaultDatasourceTenantDatabaseNameGenerator(environment, mongoTenantProperties);
    }


    @Bean
    public DatasourceDynamicTableNameInnerInterceptor datasourceDynamicTableNameInnerInterceptor(DatasourceContextHolder holder){
        return new DatasourceDynamicTableNameInnerInterceptor(holder);
    }

    @Bean
    public MybatisPlusTenantInterceptor mybatisPlusTenantInterceptor(DatasourceDynamicTableNameInnerInterceptor innerInterceptor){
        return new MybatisPlusTenantInterceptor(innerInterceptor);
    }




}
